package jwt;

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class LoadRSAPublicKeyFromPEM {
    public static void main(String[] args) throws Exception {
        // 读取 PEM 文件内容
        StringBuilder pemContent = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader("public.pem"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("-----")) continue; // 忽略 PEM 头和尾
                pemContent.append(line.trim());
            }
        }

        // 解码 Base64 内容
        byte[] keyBytes = Base64.getDecoder().decode(pemContent.toString());

        // 转换为 RSAPublicKey
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        System.out.println("RSAPublicKey: " + publicKey);
    }

    public static RSAPublicKey getPublicKey() throws Exception{
        // 读取 PEM 文件内容
        StringBuilder pemContent = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader("public.pem"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("-----")) continue; // 忽略 PEM 头和尾
                pemContent.append(line.trim());
            }
        }

        // 解码 Base64 内容
        byte[] keyBytes = Base64.getDecoder().decode(pemContent.toString());

        // 转换为 RSAPublicKey
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        return (RSAPublicKey)publicKey;
    }

    public static RSAPrivateKey getPrivateKey() throws Exception{
        // 读取 PEM 文件内容
        StringBuilder pemContent = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader("public.pem"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("-----")) continue; // 忽略 PEM 头和尾
                pemContent.append(line.trim());
            }
        }

        // 解码 Base64 内容
        byte[] keyBytes = Base64.getDecoder().decode(pemContent.toString());

        // 转换为 RSAPublicKey
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PrivateKey publicKey = keyFactory.generatePrivate(keySpec);

        return (RSAPrivateKey)publicKey;
    }
}
